//
//  String+Extension.swift
//  swiftProject
//
//  Created by ZhangSai on 2021/5/12.
//

import Foundation
import UIKit

extension String {
    
    func getWidth(_ font:UIFont) -> CGFloat {
        let textString = NSString.init(string: self)
        let textSizeWidth = textString.boundingRect(with: CGSize.init(width: UIScreen.main.bounds.size.width - 40, height: 15), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font:font], context: nil).size.width + 15
        
        return textSizeWidth
    }
    
    func getCurrentTimerByTimezone(dateFormat:String) -> String {
        let dateFormatter = DateFormatter.init()
        
        //东八区转 date
        dateFormatter.timeZone = NSTimeZone.init(name: "Asia/Shanghai") as TimeZone?
        dateFormatter.dateFormat = dateFormat
        dateFormatter.locale = NSLocale.system
        let date:Date = dateFormatter.date(from: self)!
        //date 转当前时区的 时
        dateFormatter.timeZone = NSTimeZone.system
        let time = dateFormatter.string(from: date)
        return time
    }
}

extension NSObject {
    func currentViewController() -> (UIViewController?) {
       var window = UIApplication.shared.keyWindow
       if window?.windowLevel != UIWindow.Level.normal{
         let windows = UIApplication.shared.windows
         for  windowTemp in windows{
           if windowTemp.windowLevel == UIWindow.Level.normal{
              window = windowTemp
              break
            }
          }
        }
       let vc = window?.rootViewController
       return currentViewController(vc)
    }


    func currentViewController(_ vc :UIViewController?) -> UIViewController? {
       if vc == nil {
          return nil
       }
       if let presentVC = vc?.presentedViewController {
          return currentViewController(presentVC)
       }
       else if let tabVC = vc as? UITabBarController {
          if let selectVC = tabVC.selectedViewController {
              return currentViewController(selectVC)
           }
           return nil
        }
        else if let naiVC = vc as? UINavigationController {
           return currentViewController(naiVC.visibleViewController)
        }
        else {
           return vc
        }
     }

}
